' {$STAMP BS2e}
' {$PBASIC 2.5}

'THIS IS THE MAIN TRIAL OF THE PROGRAM

' -----[ I/O Definitions ]-------------------------------------------------

  'RFID PINS
Enable          PIN     0                       ' low = reader on
RXrf            PIN     1                       ' serial from reader
Spkr            PIN     2                       ' speaker output
Latch           PIN     3                       ' lock/latch control

  'DATA LOGGER PINS
TX              PIN     8               ' Transmit Data   --> 27937.4 (RXD)
RTS             PIN     9               ' Request To Send --> 27937.6 (CTS)
RX              PIN     10              ' Receive Data    <-- 27937.5 (TXD)
CTS             PIN     11              ' Clear To Send   <-- 27937.2 (RTS)

  'Clock
DataIO          PIN     6               ' DS1302.6
Clock           PIN     7               ' DS1302.7
CS1302          PIN     5               ' DS1302.5


' -----[ Constants ]-------------------------------------------------------

  'RFID RELATED
#SELECT $STAMP
  #CASE BS2, BS2E, BS2PE
    T1200       CON     813
    T2400       CON     396
    T4800       CON     188
    T9600       CON     84
    T19K2       CON     32
    TMidi       CON     12
    T38K4       CON     6
  #CASE BS2SX, BS2P
    T1200       CON     2063
    T2400       CON     1021
    T4800       CON     500
    T9600       CON     240
    T19K2       CON     110
    TMidi       CON     60
    T38K4       CON     45
  #CASE BS2PX
    T1200       CON     3313
    T2400       CON     1646
    T4800       CON     813
    T9600       CON     396
    T19K2       CON     188
    TMidi       CON     108
    T38K4       CON     84
#ENDSELECT

SevenBit        CON     $2000
Inverted        CON     $4000
Open            CON     $8000
Baud            CON     T2400


#SELECT $STAMP
  #CASE BS2, BS2E
    TmAdj       CON     $100                    ' x 1.0 (time adjust)
    FrAdj       CON     $100                    ' x 1.0 (freq adjust)
  #CASE BS2SX
    TmAdj       CON     $280                    ' x 2.5
    FrAdj       CON     $066                    ' x 0.4
  #CASE BS2P
    TmAdj       CON     $3C5                    ' x 3.77
    FrAdj       CON     $044                    ' x 0.265
  #CASE BS2PE
    TmAdj       CON     $100                    ' x 1.0
    FrAdj       CON     $0AA                    ' x 0.665
  #CASE BS2PX
    TmAdj       CON     $607                    ' x 6.03
    FrAdj       CON     $2A                     ' x 0.166
#ENDSELECT


LastTag         CON     3


#DEFINE __No_SPRAM = ($STAMP < BS2P)            ' does module have SPRAM?




  'DATA LOGGER
BaudDL          CON     84              ' Serial Baud Rate 9600 bps (BS2)
enter           CON     0



  'Clock

WrSecs          CON     $80             ' Write Seconds
RdSecs          CON     $81             ' Read Seconds
WrMins          CON     $82             ' Write Minutes
RdMins          CON     $83             ' Read Minutes
WrHrs           CON     $84             ' Write Hours
RdHrs           CON     $85             ' Read Hours
CWPr            CON     $8E             ' Write Protect Register
WPr1            CON     $80             ' Set Write Protect
WPr0            CON     $00             ' Clear Write Protect
Hr24            CON     0               ' 24 Hour Mode


' -----[ Variables ]-------------------------------------------------------
  'RFID RELATED
#IF __No_SPRAM #THEN
  buf           VAR     Byte(10)                ' RFID bytes buffer
#ELSE
  chkChar       VAR     Byte                    ' character to test
#ENDIF

tagNum          VAR     Nib                     ' from EEPROM table
idx             VAR     Byte                    ' tag byte index
char            VAR     Byte                    ' character from table



  'DATA LOGGER
timeout         VAR     Bit             ' Timeout Inidicator
                                                                 'this is where the buffer was
index           VAR     Byte            ' Index Variable
ioByte          VAR     Byte            ' Input/Output Storage


  'Clock

reg             VAR     Byte            ' Read/Write Address
secs            VAR     Byte            ' Seconds
secs01          VAR     secs.LOWNIB
secs10          VAR     secs.HIGHNIB
mins            VAR     Byte            ' Minutes
mins01          VAR     mins.LOWNIB
mins10          VAR     mins.HIGHNIB
hrs             VAR     Byte            ' Hours
hrs01           VAR     hrs.LOWNIB
hrs10           VAR     hrs.HIGHNIB
date            VAR     Byte
month           VAR     Byte
day             VAR     Nib             ' Day
year            VAR     Byte            ' Year

work            VAR     Byte            ' Work Data


' -----[ EEPROM Data ]-----------------------------------------------------

Tag1            DATA    "25005FED2D"            ' valid tags
Tag2            DATA    "210083A266"                                     'here is where you register the user information

Name0           DATA    "Unauthorized", CR, 0
Name1           DATA    "Tag 1 (White Card)Ivan", CR, 0
Name2           DATA    "Tag 2 (Small Round)Sugu", CR, 0
Name3           DATA    "Unauthorized", CR, 0




' -----[ Initialization RFID READER ]--------------------------------------------------

Reset:
  HIGH Enable                                   ' turn of RFID reader
  LOW Latch                                     ' lock the door!
  DEBUG CR, "Turn the RFID reader", CR

' -----[ Initialization DATA LOGGER ]--------------------------------------------------

DEBUG CLS, "our own test", CR, CR
PAUSE 2000                              ' Allow Time To Settle

HIGH TX                                 ' Initialize Transmit Line
LOW RTS                                 ' Take Vinculum Out Of Reset

PAUSE 2000                              ' Allow Time To Settle

GOSUB Purge                             ' Purge Buffer
DEBUG "Synchronizing...", CR
index = 0

' For Synchronization send E until echoed back
DO WHILE (index < 1)
  PAUSE 500
  SEROUT  TX\CTS, BaudDL, ["E", CR]       ' Transmit "E CR"
  GOSUB Get_Serial_Bytes                ' Get Returned Data
LOOP
GOSUB Purge                             ' Purge Buffer

' Send e to complete synchronization
PAUSE 500
SEROUT  TX\CTS, BaudDL, ["e", CR]         ' Transmit "e CR"
GOSUB Get_Serial_Bytes

' Send CR to see if drive is present
PAUSE 500
GOSUB Purge                             ' Purge Buffer
DEBUG "Checking for USB Flash drive...", CR
SEROUT TX\CTS, BaudDL, [CR]               ' Send Carriage Return
GOSUB Get_Serial_Bytes                  ' Wait for D:\>

IF (buf(0) = "N") THEN
  DEBUG "No drive present!"
  STOP
ELSE
  DEBUG "Drive D: Ready...", CR
ENDIF
GOSUB Purge                             ' Purge Buffer


 ' -----[ Initialization Clock ]--------------------------------------------------

Init:
  reg = CWPr                            ' Initialize DS1302
  ioByte = WPr0                         ' Clear Write Protect
  GOSUB RTC_Out                         ' Send Command






' -----[ Program Code ]----------------------------------------------------

  'Setting the clock
  DEBUG CR, "You are about to set the time!",CR
  PAUSE 500
  DEBUG CLS
  DEBUG CRSRXY, 0, 0, "Enter 2 digit year, i.e. 05 = 2005:", CR
  DEBUGIN HEX2 year                     ' Set Year
  DEBUG CRSRXY, 0, 1, "Enter 2 digit month, i.e. 03 = March:", CR
  DEBUGIN HEX2 month                    ' Set Month
  DEBUG CRSRXY, 0, 2, "Enter 2 digit date, i.e. 02 = 2nd:", CR
  DEBUGIN HEX2 date                     ' Set Date
  DEBUG CR, "this is a 24hr Clock please continue with the setup",CR
  PAUSE 1000
  DEBUG CLS
  DEBUG CRSRXY, 0, 6, "Enter 2 digit hour, 00-23:", CR
  DEBUGIN HEX2 hrs                    ' Set Hours (24 Hour Mode)
  DEBUG CRSRXY, 0, 8, "Enter 2 digit minutes, 00-59:", CR
  DEBUGIN HEX2 mins                     ' Set Minutes
  DEBUG CRSRXY, 0, 9, "Press ENTER to set time.", CR
  DEBUGIN work
  DEBUG CR, "you have succesfuly setup the clock :D !!"


Main:
  DEBUG CR, "Activating the Reader",CR
  LOW Enable                                    ' activate the reader
  #IF __No_SPRAM #THEN
    SERIN RXrf, T2400, [WAIT($0A), STR buf\10]    ' wait for hdr + ID
  #ELSE
    SERIN RXrf, T2400, [WAIT($0A), SPSTR 10]
  #ENDIF
  HIGH Enable                                   ' deactivate reader
  DEBUG CR, "Deactivating reader",CR

Check_List:
  FOR tagNum = 1 TO LastTag                     ' scan through known tags
    FOR idx = 0 TO 9                            ' scan bytes in tag
      READ (tagNum - 1 * 10 + idx), char        ' get tag data from table
      #IF __No_SPRAM #THEN
        IF (char <> buf(idx)) THEN Bad_Char     ' compare tag to table
      #ELSE
        GET idx, chkChar                        ' read char from SPRAM
        IF (char <> chkChar) THEN Bad_Char      ' compare to table
      #ENDIF
    NEXT
    GOTO Tag_Found                              ' all bytes match!

Bad_Char:                                       ' try next tag
  NEXT

Bad_Tag:
  tagNum = 0
  GOSUB Show_Name                               ' print message
  FREQOUT Spkr, 1000 */ TmAdj, 115 */ FrAdj     ' groan
  PAUSE 1000
  GOTO Main

Tag_Found:
  GOSUB Show_Name                               ' print name
  HIGH Latch                                    ' remove latch
  FREQOUT Spkr, 2000 */ TmAdj, 880 */ FrAdj     ' beep
  LOW Latch                                     ' restore latch
  GOTO Main

  END











' -----[ Subroutines ]-----------------------------------------------------

' Prints name associated with RFID tag

Show_Name:
  DEBUG DEC tagNum, ": "
  LOOKUP tagNum,
         [Name0, Name1, Name2, Name3], idx      ' point to first character
  ' Open SEEDFILE.TXT for output (write)
  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["OPW newfile.txt", CR]
  GOSUB Get_Serial_Bytes
  DEBUG CR, "opening File"




  DO
    READ idx, char                              ' read character from name
    IF (char = 0) THEN EXIT                     ' if 0, we're done
    DEBUG char                                  ' otherwise print it


    PAUSE 1
    SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D, char, CR]
    GOSUB Get_Serial_Bytes
    idx = idx + 1                               ' point to next character
  LOOP


  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D,DEC2 month, CR]
  GOSUB Get_Serial_Bytes

  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D,DEC2 day,CR]
  GOSUB Get_Serial_Bytes

  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D,DEC2 year,CR]
  GOSUB Get_Serial_Bytes

  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D,DEC2 hrs,CR]
  GOSUB Get_Serial_Bytes
  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D,DEC2 mins,CR]
  GOSUB Get_Serial_Bytes

  PAUSE 2
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D,CR]
  GOSUB Get_Serial_Bytes
  DEBUG CR, "writing succesfull"


  ' Close SEEDFILE.TXT
  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["CLF newfile.txt", CR]
  GOSUB Get_Serial_Bytes
  GOSUB Purge                           ' Purge Buffer
  DEBUG CR, "file closed"

  RETURN



' -----[ Subroutines DATA LOGGER]-----------------------------------------------------

Get_Serial_Bytes:
  timeout = 1                           ' Set Timeout Indicator Flag
  index = 0                             ' Initialize Index
  DO WHILE (timeout > 0)                ' While Timeout Has Not Occurred
    ioByte = 0                          ' Clear Temporary Storage
    SERIN RX\RTS, BaudDL, 100, No_Data, [ioByte]
    buf(index) = ioByte              ' Save Byte Received To Array
    index = index + 1                   ' Increment Index
    IF (index > 9) THEN                ' Check For Overflow                      'changed from 14 to 9
      index = 9                        ' Prevent Overflow                        'similar change
    ENDIF
  LOOP
RETURN

Purge:
  timeout = 1                           ' Set Timeout Indicator Flag
  DO WHILE (timeout > 0)                ' While Timeout Has Not Occurred
    PAUSE 50
    SERIN RX\RTS, BaudDL, 500, No_Data, [ioByte]
  LOOP
  RETURN

No_Data:
  timeout = 0                           ' Timeout, Clear Flag
RETURN

No_Data2:
  DEBUG CR, "Error reading the seed file -- Halting execution!", CR
  PAUSE 1000
  GOSUB Purge                           ' Purge Buffer
  STOP
RETURN




' -----[ Subroutines Clock]-----------------------------------------------------

RTC_Out:
  HIGH CS1302                           ' Select DS1302
  SHIFTOUT DataIO, Clock, LSBFIRST, [reg, ioByte]
  LOW CS1302                            ' Deselect DS1302
  RETURN 